<template>
  <div class="ek-checkbox">
    <div v-if="loading">加载中...</div>
    <el-checkbox-group v-model="value" @change="change" :disabled="disabled" :size="size">
      <el-checkbox  v-for="item in ekOptions" :key="item.value" :label="item.value"  :value="item.value">{{ item.label }}</el-checkbox>
    </el-checkbox-group>
  </div>
</template>

<script setup> 
import {
  getCurrentInstance,
  defineComponent,
  defineEmits,
  computed,
  ref,
  reactive
} from "vue";

const props = defineProps({
  // 值
  modelValue:{
    type: Array,
    default: () => [], 
  },
  // 禁用
  disabled: {
    type: Boolean,
    default: false,
  },
  // 远程地址,存在远程地址，则优先从远程地址获取数据
  url: {
    type: String,
    default: '',
  },
  //选项，选项里面必须包含label和value
  options: {
    type: Array,
    default: () => [],  
  },
  size: {
    type: String,
    default: 'default'
  }

});

const {
  appContext: {
    config: { globalProperties },
  },
} = getCurrentInstance();
const { $storage, $http } = globalProperties;

const emit = defineEmits(['update:modelValue','change'])

const value = computed({
  get() {
    return props.modelValue
  },
  set(value) {
    emit('update:modelValue', value)
  }
})

const change = (event) => {
  emit('change', event)
};

// 选项列表
const ekOptions =  computed(() => {
  if(props.url){
    return remoteData.value;
  } else {
    return props.options
  }
});

function init(){
  if(props.url){
    getData(props.url);
  }
}
const loading = ref(false)
const remoteData = ref([]);
function getData(url) {
  loading.value = true
  $http.get(url).then((res)=>{
    if(res.status === 'success'){
      if(res.data?.length){
        remoteData.value = res.data;
      }
    }
  }).finally(()=>{
    loading.value = false
  })
}

init();



</script>

<style scoped lang="scss"></style>
